package ywh.pool
{
	import ywh.event.CoreEvent;
	import ywh.list.MediaList;
	import ywh.manager.Core;
	import ywh.manager.CoreState;
	import ywh.manager.Tag;
	import ywh.player.AbstractShower;
	import ywh.stream.FollowStream;
	import ywh.stream.MainStream;
	import ywh.stream.MediaStream;
	import ywh.utils.XMLUtils;
	
	/**
	 * 媒体流池;
	 * @author 杨伟华
	 * @version 1.0
	 *
	 * Created 1/21/2013 4:40 PM
	 */
	public class StreamPool
	{
		static private var _id2StreamMap:Object;
		static private var _activeStreams:Vector.<FollowStream>;
		static private var _usableStreams:Vector.<FollowStream>;
		{
			_activeStreams = new Vector.<FollowStream>();
			_usableStreams = new Vector.<FollowStream>();
		}
		
		public function StreamPool()
		{
			throw(new Error("StreamPool类是静态类"));
		}
		
		/**
		 * 初始化所有流
		 * @param	streamInfos 流信息
		 */
		static public function initStreams(streamInfos:XMLList):void
		{
			if (_id2StreamMap)
			{
				destoryStreams();
			}
			var count:int = streamInfos.length();
			_id2StreamMap = {};
			initStream(mainStream, streamInfos[0])
			for (var i = 1; i < count; i++)
			{
				var fs:FollowStream = getFollowStream();
				initStream(fs, streamInfos[i]);
				_activeStreams.push(fs);
			}
			Core.state = CoreState.STREAMS_READY;
		}
		
		/**
		 * 语句名称获取流,本方法应该用于在初始化流之后,
		 * @param	id
		 * @return
		 */
		static public function getStreamById(id:String):MediaStream
		{
			return _id2StreamMap[id] as MediaStream;
		}
		
		/**
		 * 获取主要流;
		 */
		static public function get mainStream():MainStream
		{
			return MainStream.$;
		}
		
		static private function initStream(stream:MediaStream, streamInfo:XML):void
		{
			var streamId:String = XMLUtils.getPropString(streamInfo, Tag._STREAM_ID);
			var playerId:String = XMLUtils.getPropString(streamInfo, Tag._PLAYER_ID);
			var listId:String = XMLUtils.getPropString(streamInfo, Tag._LIST_ID);
			var streamPlayer:AbstractShower = PlayerPool.getPlayerById(playerId);
			var streamList:MediaList = ListPool.getListById(listId);
			stream.initStream(streamList, streamPlayer);
			_id2StreamMap[streamId] = stream;
		}
		
		/**
		 * 清空所有流的数据;
		 */
		static private function destoryStreams():void
		{
			mainStream.destoryStream();
			var fs:FollowStream;
			_id2StreamMap = {};
			while (_activeStreams.length)
			{
				fs = _activeStreams.pop();
				fs.destoryStream();
				_usableStreams.push(fs);
			}
		}
		
		static private function getFollowStream():FollowStream
		{
			if (_usableStreams.length > 0)
			{
				return _usableStreams.pop();
			}
			else
			{
				return new FollowStream();
			}
		}
	}

}